package com.cwf.business.activity.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.cwf.business.MyApplication;
import com.cwf.business.R;
import com.cwf.business.activity.activitys.ChooseCityActivity;
import com.cwf.business.permission.FePermissions;
import com.cwf.business.permission.PermissionCode;
import com.cwf.business.permission.PermissionGranted;
import com.cwf.business.permission.PermissionSettingDialog;
import com.cwf.business.preferences.PreferencesUtils;
import com.cwf.business.util.choosecity.utils.StringUtils;
import com.cwf.business.view.banner.OnItemClickListener;
import com.cwf.business.view.banner.RollPagerView;
import com.cwf.business.view.banner.adapter.LoopPagerAdapter;
import com.cwf.business.view.dropdownMenu.MainActivity;
import com.cwf.business.view.refreshlayout.RefreshListenerAdapter;
import com.cwf.business.view.refreshlayout.TwinklingRefreshLayout;
import com.cwf.business.view.searchbox.SearchFragment;

import static android.app.Activity.RESULT_OK;

/**
 * 首页
 * Created by sam_chan on 2017/5/16.
 */
public class HomeFragment extends Fragment {

    private static final int REQUEST_CODE_PICK_CITY = 2;
    private AMapLocationClient mLocationClient;
    private LinearLayout mCityChooseLayout;
    private TextView mCityChoose;
    private TextView mSearchTextview;
    private SearchFragment searchFragment;

    private RollPagerView mViewPager;
    private TwinklingRefreshLayout refreshLayout;

    private LinearLayout mFreerMore;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getActivity().overridePendingTransition(android.R.anim.slide_in_left,
                android.R.anim.slide_out_right);
        View homeView = inflater.inflate(R.layout.fragment_home,
                container, false);
        mCityChoose = (TextView) homeView.findViewById(R.id.city_choose);
        mCityChooseLayout = (LinearLayout) homeView.findViewById(R.id.city_choose_layout);
        mSearchTextview = (TextView) homeView.findViewById(R.id.search_textview);
        searchFragment = SearchFragment.newInstance();

        mViewPager = (RollPagerView) homeView.findViewById(R.id.view_pager);
        mViewPager.setAdapter(new ImageLoopAdapter(mViewPager));

        refreshLayout = (TwinklingRefreshLayout) homeView.findViewById(R.id.refresh);

        mFreerMore = (LinearLayout) homeView.findViewById(R.id.freer_more);

        return homeView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        FePermissions.with(getActivity())
                .requestCode(PermissionCode.LOCATION)
                .rationaleMessage(getResources().getString(R.string.permission_rationale_location))
                .permissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION})
                .request();

        bindData();
        initEvent();
    }

    /**
     * 获取城市位置
     */
    private void getCity() {
        mLocationClient = MyApplication.getAMapLocationClient();
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getContext());
        }

        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        String location = StringUtils.extractLocation(city, district);
                        mCityChoose.setText(location);
                        PreferencesUtils.getInstance().putPreferences(PreferencesUtils.SAVE_LASTTIME_CITY, location);
                    } else {
                        //定位失败
                        mCityChoose.setText(getResources().getString(R.string.cp_no_city));
                    }
                }
            }
        });
        mLocationClient.startLocation();

    }

    private void bindData() {
        mCityChoose.setText(PreferencesUtils.getInstance().getPreferences(PreferencesUtils.SAVE_LASTTIME_CITY, getResources().getString(R.string.cp_no_city)));
/*
        List<BannerInfo> lists = new ArrayList<>();
        BannerInfo info1 = new BannerInfo();
        info1.setUrl("http://img3.imgtn.bdimg.com/it/u=1749061261,2462112140&fm=21&gp=0.jpg");
        info1.setName("寒冰射手");
        lists.add(info1);
        BannerInfo info2 = new BannerInfo();
        info2.setUrl("http://img5.imgtn.bdimg.com/it/u=1949438216,3782070973&fm=23&gp=0.jpg");
        info2.setName("齐天大圣");
        lists.add(info2);
        BannerInfo info3 = new BannerInfo();
        info3.setUrl("http://imgs.91danji.com/Upload/201419/2014191037351347278.jpg");
        info3.setName("放逐之刃");
        lists.add(info3);
        list = lists;
        title.setVisibility(View.VISIBLE);
        autoBannerAdapter.changeItems(list);
        autoBannerView.setAdapter(autoBannerAdapter);
    }*/
    }

    private void initEvent() {
        //选择城市
        mCityChooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getContext(), ChooseCityActivity.class),
                        REQUEST_CODE_PICK_CITY);
            }
        });

        //搜索
        mSearchTextview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchFragment.show(getActivity().getSupportFragmentManager(), SearchFragment.TAG);
            }
        });

        //banner
        mViewPager.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Toast.makeText(getContext(), "Item " + position + " clicked", Toast.LENGTH_SHORT).show();
            }
        });

        //刷新
        refreshLayout.setOverScrollRefreshShow(false);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout1) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishRefreshing();
                    }
                }, 4000);
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout1) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishLoadmore();
                    }
                }, 4000);
            }
        });

        //更多
        mFreerMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), MainActivity.class));
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                String city = data.getStringExtra(ChooseCityActivity.KEY_PICKED_CITY);
                if (city != null && !"".equals(city)) {
                    PreferencesUtils.getInstance().putPreferences(PreferencesUtils.SAVE_LASTTIME_CITY, city);
                    mCityChoose.setText(city);
                } else {
                    mCityChoose.setText(getResources().getString(R.string.cp_no_city));
                }
            }
        }
    }

    private class ImageLoopAdapter extends LoopPagerAdapter {
        int[] imgs = new int[]{
                R.drawable.banner_img1,
                R.drawable.banner_img2,
                R.drawable.banner_img3,
        };

        public ImageLoopAdapter(RollPagerView viewPager) {
            super(viewPager);
        }

        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view = new ImageView(container.getContext());
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            view.setImageResource(imgs[position]);
            return view;
        }

        @Override
        public int getRealCount() {
            return imgs.length;
        }
    }

    @PermissionGranted(PermissionCode.LOCATION)
    public void onLocationPermissionGranted() {
        //获取城市位置
        new Thread(new Runnable() {
            @Override
            public void run() {
                getCity();
            }
        }).start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FePermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults, (requestCode1, permissions1, grantResults1, deniedMessage) -> new PermissionSettingDialog.Builder(getActivity())
                .setCancelable(false)
                .setMessage(getResources().getString(R.string.permission_msg_request_failed_location))
                .setNeutralText(getResources().getString(R.string.permission_text_go_setting))
                .setPositiveText(getResources().getString(R.string.permission_text_i_know))
                .setPositiveListener(v -> getActivity().finish())
                .build()
                .show());
    }
}
